const { existsSync, mkdirSync } = require('fs');
const path = require('path');

// 确保上传目录存在
const uploadDir = path.join(process.cwd(), 'public', 'uploads');
if (!existsSync(uploadDir)) {
  try {
    mkdirSync(uploadDir, { recursive: true });
    console.log('创建上传目录成功:', uploadDir);
  } catch (error) {
    console.error('创建上传目录失败:', error);
  }
}

/** @type {import('next').NextConfig} */
const nextConfig = {
  // 禁用压缩，减少构建复杂度
  compress: false,
  // 关闭模块提升，减少打包问题
  poweredByHeader: false,
  // 禁用sourcemap，提高构建速度
  productionBrowserSourceMaps: false,
  // 确保正确处理静态文件
  distDir: '.next',
  // 修复跨域问题
  headers: async () => {
    return [
      {
        source: '/:path*',
        headers: [
          { key: 'X-DNS-Prefetch-Control', value: 'on' },
          { key: 'X-XSS-Protection', value: '1; mode=block' }
        ]
      }
    ];
  },
  // 图像配置
  images: {
    unoptimized: true, // 禁用图像优化，避免构建问题
    domains: [
      'localhost',
      '127.0.0.1',
      'storage.googleapis.com',
      'avatars.githubusercontent.com',
      'lh3.googleusercontent.com'
    ],
    remotePatterns: [
      {
        protocol: 'https',
        hostname: '**',
      },
      {
        protocol: 'http',
        hostname: 'localhost',
      },
      {
        protocol: 'http',
        hostname: '127.0.0.1',
      }
    ],
    dangerouslyAllowSVG: true,
  },
  
  // 环境变量配置
  env: {
    NEXTAUTH_URL: process.env.NEXTAUTH_URL || 'http://localhost:3000',
    NEXTAUTH_SECRET: process.env.NEXTAUTH_SECRET,
  },

  // 从experimental移到根级别
  serverExternalPackages: ['@prisma/client', 'bcrypt'],
  outputFileTracingIncludes: {
    '/api/**/*': ['node_modules/bcrypt/**/*'],
  },

  // webpack配置
  webpack: (config, { isServer }) => {
    // 针对服务器端的DNS设置
    if (isServer) {
      config.resolve = {
        ...config.resolve,
        preferRelative: true,
        alias: {
          ...config.resolve.alias,
          '@': path.resolve(__dirname, './src')
        }
      };
    } else {
      // 客户端特定配置
      config.resolve = {
        ...config.resolve,
        alias: {
          ...config.resolve.alias,
          '@': path.resolve(__dirname, './src')
        },
        fallback: {
          ...config.resolve.fallback,
          fs: false,
          path: false,
          os: false
        }
      };
    }
    
    // 设置node环境
    config.node = {
      ...config.node,
      __dirname: true,
    };

    return config;
  },
  
  // 禁用严格模式
  reactStrictMode: false,
};

module.exports = nextConfig;
